import React from 'react'
import { Card, Row, Col, Tree, Button, message } from 'antd'
import Utils from '../../utils/utils'
import ETable from '../../components/ETable/index'
import { axhttp } from '../../utils/axhttp';
import BaseForm from '../../components/BaseForm';
import { dictionary } from '../../utils/dictionary';

const TreeNode = Tree.TreeNode;
const url = {
    read: '/api/role/read',
}
const urlMenu = {
    readx: '/api/menu/readx',
    updateJson: '/api/menu/updateJson',
}
export default class Index extends React.Component {
    /** 状态数据 */
    state = {
        /** 操作类型（新增、修改） */
        operateType: undefined,
        /** 数据的加载状态（是否在加载中） */
        loading: false,
        loadingMenu: false,
        /** 请求参数 */
        params: {},
        paramsMenu: {},
        /** 列表数据 */
        data: { list: [], pagination: false },
        /** 菜单数据 */
        dataMenu: [],
        /** 角色用于的菜单权限 */
        checkedKeys: [],
    }

    /** 查询表单字段 */
    searchFormFields = [
        {
            type: 'input',
            label: '角色名',
            field: 'roleName',
            width: 80,
        },
    ]

    /** 配置列头 */
    columns = [{
        title: '角色名',
        dataIndex: 'roleName',
        width: 108,
        ellipsis: true,
        sorter: false,
    }
    ]

    /** 挂载函数 */
    componentDidMount() {
        this.handleRead();
        this.handleReadMenu();
    }

    /** 读取处理函数 */
    handleRead = (params) => {
        this.setState({
            loading: true,   //将loading状态设置为加载中
            params           //将请求参数保存到状态数据中
        });

        axhttp.getListXhr(url.read, params).then(res => {
            this.setState({ data: res });
        }).finally(() => {
            this.setState({
                loading: false, //将loading状态设置为加载完成
            });
        });
    }

    getCheckedKeys = (roleId, menu) => {
        const keys = [];
        menu.forEach(i => {
            if (i.roles && i.roles.indexOf(roleId) > -1) {
                keys.push(i.key);
            }
            if (i.children) {
                keys.push(...this.getCheckedKeys(roleId, i.children));
            }
        });
        return keys;
    }

    /** 读取菜单处理函数 */
    handleReadMenu = (params = {}) => {
        this.setState({
            loadingMenu: true,   //将loading状态设置为加载中
            paramsMenu: {        //将请求参数保存到状态数据中
                roleId: params.id,
                roleName: params.roleName,
            }
        });

        axhttp.getListXhr(urlMenu.readx).then(res => {
            const menu = res.data;
            const keys = this.getCheckedKeys(params.id, menu);
            this.setState({ dataMenu: menu, checkedKeys: keys });
        }).finally(() => {
            this.setState({
                loadingMenu: false, //将loading状态设置为加载完成
            });
        });
    }

    /** 渲染菜单树 */
    renderTreeNodes = data => data.map(item => {
        if (item.children) {
            return (
                <TreeNode title={item.title} key={item.key} dataRef={item}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode key={item.path} {...item} />;
    });

    /** 选中角色行信息 */
    handleSelectedItem = (keys, rows, ids) => {
        Utils.updateSelectedItem.call(this, keys, rows, ids);
        this.handleReadMenu(rows);
    }

    /** 选中菜单 */
    handleCheck = (keys) => {
        this.setState({ checkedKeys: keys });
    }

    /** 根据选中的菜单，更新菜单数据 */
    handleUpdateMenuData = (keys, menu, roleId) => {
        menu.forEach(i => {
            let roles = [];
            if (i.roles) {
                roles = i.roles.split(',');
            }
            /** 先删除该菜单的角色 */
            const idx = roles.findIndex(j => j === roleId);
            if (idx > -1) {
                roles.splice(idx, 1);
            }
            /** 如果该菜单时选中状态，将角色Id加入该菜单中 */
            if (keys.find(j => j === i.key)) {
                roles.push(roleId);
            }
            i.roles = roles.join(',');

            if (i.children) {
                this.handleUpdateMenuData(keys, i.children, roleId);
            }
        });
    }

    /** 保存菜单 */
    handleUpdateMenu = () => {
        const { checkedKeys, dataMenu, paramsMenu } = this.state;
        this.handleUpdateMenuData(checkedKeys, dataMenu, paramsMenu.roleId);

        axhttp.postFormXhr(urlMenu.updateJson, {
            json: JSON.stringify(dataMenu)
        }).then(() => {
            message.success('保存成功');
        });
    }

    render() {
        const { loading, selectedRowKeys, data, paramsMenu, checkedKeys, dataMenu } = this.state;

        return (
            <div>
                <Card>
                    <BaseForm formList={this.searchFormFields} filterSubmit={this.handleRead} />
                </Card>
                <div className="content-wrap">
                    <Row>
                        <Col span={8}>
                            <Card title='角色信息' bodyStyle={{ padding: 0 }}>
                                <ETable
                                    loading={loading}
                                    columns={this.columns}
                                    rowSelection='radio'
                                    updateSelectedItem={this.handleSelectedItem}
                                    selectedRowKeys={selectedRowKeys}
                                    data={data}
                                    handleRead={this.handleRead}
                                />
                            </Card>
                        </Col>
                        <Col span={16}>
                            <Card title={`${paramsMenu.roleName ? (paramsMenu.roleName + ' - ') : ''}菜单权限`}>
                                <Tree
                                    checkable
                                    // onExpand={this.onExpand}
                                    // expandedKeys={this.state.expandedKeys}
                                    // autoExpandParent={this.state.autoExpandParent}
                                    onCheck={this.handleCheck}
                                    checkedKeys={checkedKeys}
                                // onSelect={this.onSelect}
                                // selectedKeys={this.state.selectedKeys}
                                >
                                    {this.renderTreeNodes(dataMenu)}
                                </Tree>
                                <Button type='primary' icon='save' style={{ float: 'right' }} onClick={this.handleUpdateMenu} disabled={!paramsMenu.roleId}>
                                    保存
                                </Button>
                            </Card>
                        </Col>
                    </Row>
                </div>
            </div>
        );
    }
}